package com.kk.jwt;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.entity.User;
import com.kk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author K. L. Mao
 * @create 2019/1/11
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("loadUserByUsername正在执行");
        QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("status",0);
        User user = userService.getOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        }
        //List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<GrantedAuthority> authorities=new ArrayList<>();
        authorities.add((GrantedAuthority) () -> {
            switch (user.getType()){
                case 0:
                    return "user";
                case 1:
                    return "admin";
                default:
                    return "vip";
            }
        });
        return new JwtUser(user.getId(),user.getUsername(),user.getPassword(), user.getAvatar(),user.getEmail(), user.getStatus(), authorities);
    }
}